package org.anti996.lms.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.anti996.lms.model.Warehouse;
import org.anti996.lms.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 仓库表 前端控制器
 * </p>
 *
 * @author The Anti996 Authors
 * @since 2022-07-15
 */
@Slf4j
@RestController
@RequestMapping("/lms/warehouse")
@CrossOrigin(origins = "*")
public class WarehouseController {
    @Autowired
    private WarehouseService warehouseService;

    /**
     * 获取仓库列表
     *
     * @return 仓库列表
     */
    @GetMapping
    public List<Warehouse> warehouseList() {
        return warehouseService.list();
    }

    /**
     * 获取仓库分页列表
     *
     * @param no 第no个页面
     * @param sz 每个页面的数据条数
     * @return 分页仓库列表
     */
    @GetMapping("/page/{sz}/{no}")
    public List<Warehouse> warehouseListPage(@PathVariable(name = "no") int no,
                                             @PathVariable(name = "sz") int sz) {
        Page<Warehouse> page = warehouseService.page(new Page<>(no, sz));
        return page.getRecords();
    }

    /**
     * 根据仓库编号获取仓库
     *
     * @param w_id 仓库编号
     * @return 查询到的仓库
     */
    @GetMapping("/{id}")
    public Warehouse warehouse(@PathVariable(name = "id") int w_id) {
        return warehouseService.getById(w_id);
    }

    /**
     * 创建仓库
     *
     * @param warehouse 仓库信息
     * @return 创建结果
     */
    @PostMapping(consumes = "application/json")
    public boolean insertWarehouse(@RequestBody Warehouse warehouse) {
        return warehouseService.save(warehouse);
    }

    /**
     * 更新仓库
     *
     * @param w_id      仓库编号
     * @param warehouse 新的仓库信息
     * @return 更新是否成功
     */
    @PutMapping(path = "/{id}", consumes = "application/json")
    public boolean updateWarehouse(@PathVariable(name = "id") int w_id,
                                   @RequestBody Warehouse warehouse) {
        Warehouse flag = warehouseService.getById(w_id);
        if(flag==null){return false;}
        else {
        return warehouseService.updateById(warehouse);
    }
    }

    /**
     * 删除指定仓库编号的数据
     *
     * @param w_id 仓库编号
     * @return 是否删除成功
     */
    @DeleteMapping("/{id}")
    public boolean removeWarehouse(@PathVariable(name = "id") int w_id) {
        return warehouseService.removeById(w_id);
    }

    //根据仓库名得到仓库编号
    @GetMapping("/get/{name}")
    public int getIdbywname(@PathVariable(name = "name") String name){
        return warehouseService.getIdbywname(name).getWId();
    }

    @GetMapping("/find")
    public List<String> findNamesByKeyword(@RequestParam(name = "name") String name) {
        return warehouseService.getNamesByKeyword(name);
    }

}
